const dataURLtoFile = dataurl => {
    let suffix = dataurl.substring(dataurl.indexOf("data:image/"), dataurl.indexOf(";") - 1);
    let d = new Date();
    //将base64转换为文件，dataurl为base64字符串，filename为文件名（必须带后缀名，如.jpg,.png）
    var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], "cz_" + d.getTime().slice(3) + Math.floor(Math.random() * 1000) + "." + suffix, { type: mime });
};

const fileToBase64Async = (file) => {
    return new Promise((resolve, reject) => {
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
            resolve(e.target.result);
        };
    });
};


function renderContainer(
    editor,
    elemNode,
    imageVnode,
    imageInfo
) {
    const { width, height } = imageInfo

    const style = {}
    if (width) style.width = width
    if (height) style.height = height

    const containerId = genContainerId(editor, elemNode)

    return (
        `<div id=${containerId} style=${style} className="w-e-image-container">
           ${imageVnode}
        </div>`
    )
};

function genContainerId(editor, elemNode) {
    const { id } = DomEditor.findKey(editor, elemNode) // node 唯一 id
    return `w-e-image-container-${id}`
}
function getStyleValue($elem, styleKey) {
    let res = ''

    const styleStr = $elem.attr('style') || '' // 如 'line-height: 2.5; color: red;'
    const styleArr = styleStr.split(';') // 如 ['line-height: 2.5', ' color: red', '']
    const length = styleArr.length
    for (let i = 0; i < length; i++) {
        const styleItemStr = styleArr[i] // 如 'line-height: 2.5'
        if (styleItemStr) {
            const arr = styleItemStr.split(':') // ['line-height', ' 2.5']
            if (arr[0].trim() === styleKey) {
                res = arr[1].trim()
            }
        }
    }

    return res
};


function renderContainer(
    editor,
    elemNode,
    imageVnode,
    imageInfo
) {
    const { width, height } = imageInfo

    const style = {}
    if (width) style.width = width
    if (height) style.height = height

    const containerId = genContainerId(editor, elemNode)

    return h(
        "div",
        {
            props: { id: containerId, className: "w-e-image-container" }, // HTML 属性，驼峰式写法
            style: style, // style ，驼峰式写法
        },
        [imageVnode]
    )
}


function generateUUID() {
    var d = new Date().getTime();
    if (window.performance && typeof window.performance.now === "function") {
        d += performance.now(); //use high-precision timer if available
    }
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
}

var ua = navigator.userAgent.toLowerCase();
// function isPhone() {
//     if (ua.match(/android/i)) == "android") {
//         return true;
//     }
//     if (ua.match(/iPhone/i)) == "iPhone") {
//         return true
//     }
//     if (ua.match(/iPad/i)) == "iPad") {
//         return true
//     }
// }
function isBase64(str){
    console.log(str)
    if(str.indexOf('data:')!=-1 && str.indexOf('base64')!=-1 ){
        return true;
    }else{
        return false;
    }
}
function getVideoCover(file, response) {
    // 定义生成图片的宽高，其他宽高需求可以自己改
    const fileUrl = URL.createObjectURL(file);
    const videoElement = document.createElement('VIDEO');
    videoElement.preload = true;
    videoElement.autoplay = true;
    videoElement.muted = true;
    const callBack = () => {
      const { videoWidth, videoHeight } = videoElement;  // 获取video的宽高
      // let x = 0, y = 0, width = 0, height = 0;
      // // 计算缩小后图片的宽高以及canvas绘制的位置信息
      // if (videoWidth / videoHeight >= 1.5) {
      //   width = imgWidth ;
      //   height = videoHeight * (imgWidth / videoWidth);
      //   x = 0;
      //   y = (imgHeight- height) / 2;
      // } else {
      //   height = imgHeight;
      //   width = videoWidth * (imgHeight / videoHeight);
      //   y = 0;
      //   x = (imgWidth - width) / 2;
      // }
      const canvas = document.createElement('canvas');
      canvas.width = videoWidth ;
      canvas.height = videoHeight;
      const ctx = canvas.getContext('2d');
      // ctx.fillStyle = "#000";
      // ctx.fillRect(0, 0, imgWidth , imgHeight);
      ctx.drawImage(videoElement, 0, 0, videoWidth, videoHeight);
      const dataBase64 = canvas.toDataURL('image/png'); // 完成base64图片的创建
      if (dataBase64) {
        const imgFile = dataURLtoFile(dataBase64);
        if (response) {
          response(imgFile, dataBase64);
        }
      }
    };
    // videoElement.addEventListener('loadeddata', callBack);
    // videoElement.onseeked = callBack;
    videoElement.onloadeddata = setTimeout(() => {
      callBack();
    }, 1000);;
    videoElement.src = fileUrl;
  }

  function colorRGBtoHex(color) {
    
    var rgb = color.split(',');
    var r = parseInt(rgb[0].split('(')[1]);
    var g = parseInt(rgb[1]);
    var b = parseInt(rgb[2].split(')')[0]);
    var hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
    return hex;
}
